<template>
  <AdminLayout active-menu="house-verification">
    <div class="house-verification-content">
      <div class="content-header">
        <h2>房产认证审核管理</h2>
        <p>审核和管理平台上的房产认证信息</p>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-card class="filter-card">
          <el-form :model="filterForm" inline>
            <el-form-item label="审核状态">
              <el-select v-model="filterForm.verifyStatus" placeholder="选择状态" @change="handleFilter">
                <el-option label="全部" value="" />
                <el-option label="待审核" value="0" />
                <el-option label="已通过" value="1" />
                <el-option label="已驳回" value="2" />
                <el-option label="已取消" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请时间">
              <el-date-picker
                v-model="filterForm.applyTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="handleFilter"
              />
            </el-form-item>
            <el-form-item label="房产编号">
              <el-input v-model="filterForm.propertyNo" placeholder="输入房产编号" @input="handleFilter" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFilter">筛选</el-button>
              <el-button @click="resetFilter">重置</el-button>
              <el-button @click="loadVerifications">刷新</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 房产认证列表 -->
      <div class="verification-list-section">
        <el-card class="list-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span>房产认证列表 ({{ filteredVerifications.length }})</span>
              <el-button type="primary" @click="batchApprove" :disabled="selectedVerifications.length === 0">
                批量通过
              </el-button>
            </div>
          </template>

          <el-table
            :data="paginatedVerifications"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            class="verification-table"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="propertyVerifyId" label="认证ID" width="100" />
            <el-table-column prop="propertyNo" label="房产编号" width="180" />
            <el-table-column prop="propertyAddr" label="房产地址" min-width="200" />
            <el-table-column prop="userId" label="用户ID" width="100" />
            <el-table-column label="房产证图片" width="120">
              <template #default="scope">
                <el-image
                  :src="scope.row.propertyPicPath"
                  :preview-src-list="[scope.row.propertyPicPath]"
                  fit="cover"
                  style="width: 60px; height: 40px; border-radius: 4px;"
                  preview-teleported
                />
              </template>
            </el-table-column>
            <el-table-column prop="applyTime" label="申请时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.applyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="verifyStatus" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.verifyStatus)">
                  {{ getStatusText(scope.row.verifyStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDetails(scope.row)">查看</el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="approveVerification(scope.row)"
                  :disabled="scope.row.verifyStatus !== 0"
                  :loading="scope.row.approving"
                >
                  通过
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="rejectVerification(scope.row)"
                  :disabled="scope.row.verifyStatus !== 0"
                  :loading="scope.row.rejecting"
                >
                  拒绝
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="filteredVerifications.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 拒绝原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝房产认证" width="500px">
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject" :loading="rejectForm.submitting">确定拒绝</el-button>
        </span>
      </template>
    </el-dialog>
  </AdminLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdminLayout from '@/components/layout/AdminLayout.vue'
import axiosInstance from '@/main.js'

// 加载状态
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  verifyStatus: '',
  applyTimeRange: null,
  propertyNo: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 选中的认证
const selectedVerifications = ref([])

// 房产认证数据
const verifications = ref([])

// 拒绝对话框
const rejectDialogVisible = ref(false)
const rejectForm = reactive({
  propertyVerifyId: null,
  reason: '',
  submitting: false
})

// 筛选后的认证
const filteredVerifications = computed(() => {
  return verifications.value.filter(verification => {
    // 状态筛选
    if (filterForm.verifyStatus !== '' && verification.verifyStatus !== parseInt(filterForm.verifyStatus)) {
      return false
    }

    // 房产编号筛选
    if (filterForm.propertyNo && !verification.propertyNo.includes(filterForm.propertyNo)) {
      return false
    }

    // 申请时间筛选
    if (filterForm.applyTimeRange && filterForm.applyTimeRange.length === 2) {
      const applyTime = new Date(verification.applyTime)
      const startTime = new Date(filterForm.applyTimeRange[0])
      const endTime = new Date(filterForm.applyTimeRange[1])
      if (applyTime < startTime || applyTime > endTime) {
        return false
      }
    }

    return true
  })
})

// 分页后的认证
const paginatedVerifications = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredVerifications.value.slice(start, end)
})

// 加载房产认证数据
const loadVerifications = async () => {
  console.log('开始加载房产认证数据...')
  loading.value = true
  try {
    console.log('发送请求到:', '/admin/house/getAllPropertyVerification')
    const response = await axiosInstance.get('/admin/house/getAllPropertyVerification')
    console.log('收到响应:', response)

    if (response.code === '200') {
      verifications.value = response.data || []
      console.log('成功加载房产认证数据，数量:', verifications.value.length)
      ElMessage.success(`成功加载 ${verifications.value.length} 条房产认证数据`)
    } else {
      console.error('响应错误:', response)
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取房产认证数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    verifyStatus: '',
    applyTimeRange: null,
    propertyNo: ''
  })
  handleFilter()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedVerifications.value = selection
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    0: 'warning',  // 待审核
    1: 'success',  // 已通过
    2: 'danger',   // 已驳回
    3: 'info'      // 已取消
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已驳回',
    3: '已取消'
  }
  return texts[status] || status
}

// 查看详情
const viewDetails = (verification) => {
  ElMessage.info(`查看房产认证详情: ${verification.propertyNo}`)
}

// 通过房产认证
const approveVerification = async (verification) => {
  try {
    await ElMessageBox.confirm('确定通过这个房产认证吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    verification.approving = true

    const response = await axiosInstance.post(`/admin/house/passVerify/${verification.propertyVerifyId}`)

    if (response.code === '200') {
      verification.verifyStatus = 1
      ElMessage.success('房产认证审核通过')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('通过认证失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  } finally {
    verification.approving = false
  }
}

// 拒绝房产认证
const rejectVerification = (verification) => {
  rejectForm.propertyVerifyId = verification.propertyVerifyId
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }

  rejectForm.submitting = true

  try {
    const response = await axiosInstance.post(
      `/admin/house/rejectPropertyVerification/${rejectForm.propertyVerifyId}`,
      rejectForm.reason,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.code === '200') {
      // 更新本地数据
      const verification = verifications.value.find(v => v.propertyVerifyId === rejectForm.propertyVerifyId)
      if (verification) {
        verification.verifyStatus = 2
        verification.refuseReason = rejectForm.reason
      }

      ElMessage.success('房产认证已拒绝')
      rejectDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('拒绝认证失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    rejectForm.submitting = false
  }
}

// 批量通过
const batchApprove = async () => {
  const pendingVerifications = selectedVerifications.value.filter(v => v.verifyStatus === 0)

  if (pendingVerifications.length === 0) {
    ElMessage.warning('请选择待审核的认证记录')
    return
  }

  try {
    await ElMessageBox.confirm(`确定批量通过选中的 ${pendingVerifications.length} 个房产认证吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 批量调用通过接口
    const promises = pendingVerifications.map(verification =>
      axiosInstance.post(`/admin/house/passVerify/${verification.propertyVerifyId}`)
    )

    const results = await Promise.allSettled(promises)
    let successCount = 0

    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value.code === '200') {
        pendingVerifications[index].verifyStatus = 1
        successCount++
      }
    })

    ElMessage.success(`成功通过 ${successCount} 个房产认证`)
    selectedVerifications.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量通过失败:', error)
      ElMessage.error('批量操作失败，请稍后重试')
    }
  }
}

onMounted(() => {
  console.log('HouseVerification 页面已挂载，开始加载数据...')
  loadVerifications()
})
</script>

<style scoped>
.house-verification-content {
  padding: 20px;
}

.content-header {
  margin-bottom: 20px;
}

.content-header h2 {
  color: #2c3e50;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.content-header p {
  color: #7f8c8d;
  margin: 0;
  font-size: 14px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-card {
  border-radius: 8px;
}

.verification-list-section {
  margin-bottom: 20px;
}

.list-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.verification-table {
  margin-top: 16px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table tr:hover > td) {
  background-color: #f5f7fa;
}

/* 状态标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

:deep(.el-button--small) {
  padding: 5px 12px;
  font-size: 12px;
}

/* 图片样式 */
:deep(.el-image) {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-select) {
  width: 140px;
}

:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-date-editor) {
  border-radius: 6px;
}

/* 卡片样式 */
:deep(.el-card) {
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

:deep(.el-card__header) {
  background-color: #fafbfc;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>